const baseUrl = "https://enchi.io/";

let socket = "";
let currentSession = "";
let pageSessionID = "";
let currentUser = {};

//获取页面sessionID
async function getPageID() {
    let cookie = await chrome.cookies.get({ url: baseUrl, name: "pageSessionID" });
    if (!cookie || typeof cookie.value === 'undefined') return
    if (cookie.value) {
        pageSessionID = decodeURI(cookie.value)
    }
}



let heartCheck = {
    reset: function () {
        chrome.alarms.getAll(
            (alarm) => {
                if (alarm.length > 0) {
                    chrome.alarms.clearAll()
                }
            }
        )
        return this;
    },
    start: function () {
        chrome.alarms.create('checkStatus', {
            delayInMinutes: 30,
        });
        chrome.alarms.onAlarm.addListener((alarms) => {
            if (socket.readyState == 1) {
                console.log("连接状态，发送消息保持连接");
                socket.send("ping");
                // 如果获取到消息，说明连接正常，重置心跳检测
                heartCheck.reset().start();
            } else {
                console.log("断开连接，尝试重连");
                connect();
            }
        })
    }
};

function connect() {
    const host = "wss://enchi.io/metamemory/ws/myWebSocket";
    socket = new WebSocket(host);

    socket.onopen = function () {
        socket.send('getSessionID');
        heartCheck.reset().start();
    }


    socket.onmessage = function (msg) {
        let data = JSON.parse(msg.data)
        if (data.status === 1) { //注入cookies
            currentSession = JSON.stringify(data.sessionId)
            chrome.cookies.set({
                url: baseUrl,
                name: "sessionID",
                value: currentSession,
                secure: true,
            })
        } else if (data.status === 2) {//获取用户信息
            chrome.storage.sync.set({ "userInfo": JSON.stringify(data.userInfo) })
            chrome.storage.sync.set({ "isLogin": true }, () => {
                let options = {
                    type: "basic",
                    title: "login succeeded ",
                    message: "Welcome to use enchi,One click collection ultimate experience",
                    iconUrl: "../img/logo.png"
                }
                chrome.notifications.create('signIn', options)
            })
        } else if (data.status === 4) {//登出
            chrome.storage.sync.set({ "isLogin": false })
        }
    }
}

connect()

chrome.runtime.onMessage.addListener(
    async function (request, sender, sendResponse) {
        if (request.currentStep === 'getUserInfo') {
            socket.send('getUserInfo');
            chrome.tabs.query({ url: baseUrl }, (tabs) => {
                if (tabs.length > 0) {
                    let tabIds = []
                    tabs.map((item) => {
                        tabIds.push(item.id)
                    })
                    chrome.tabs.remove(tabIds)
                }
            })
            chrome.tabs.create({ url: baseUrl });
        }
        if (request.currentStep === "loginOut") {
            let cookie = await chrome.cookies.get({ url: baseUrl, name: "pageSessionID" });
            if (!cookie || typeof cookie.value === 'undefined') return
            if (cookie.value) {
                pageSessionID = decodeURI(cookie.value)
            }
            socket.send(JSON.stringify({ 'loginOut': pageSessionID }));
            let options = {
                type: "basic",
                title: "sign out succeeded ",
                message: "Looking forward to meeting you again",
                iconUrl: "../img/logo.png"
            }
            chrome.notifications.create('loginOut', options)
        }
    });

socket.onclose = function () {
    console.log(socket.readyState, 'close');
}



chrome.runtime.onInstalled.addListener(async () => {
    chrome.contextMenus.create({
        id: "ENCHI",
        title: "Add selected content to ENCHI",
        type: 'normal',
        contexts: ['selection'],
    });
});


async function SaveEntry(content, url) {
    getPageID()
    chrome.storage.sync.get('userInfo', async (data) => {
        if (!data.userInfo || typeof data.userInfo === 'undefined') return
        currentUser = JSON.parse(data.userInfo);
        const res = await fetch("https://enchi.io/metamemory/entry/saveEntry", {
            method: "post",
            headers: new Headers({
                'Content-Type': 'application/json',
                'X-Token': currentUser.token
            }),
            body: JSON.stringify({
                'content': content,
                'label': ['chrome extensions'],
                'source': url,
                'type': 1,
                'userId': currentUser.id,
            })
        }).then(response => response.text())
            .then(text => {
                console.log(text, 'text.code');
                if (JSON.parse(text).code == 200) {
                    socket.send(JSON.stringify({ 'saveEntry': pageSessionID }));
                    let options = {
                        type: "basic",
                        title: "save succeeded ",
                        message: "collection ultimate experience",
                        iconUrl: "../img/logo.png"
                    }
                    chrome.notifications.create('saveEntry', options)
                }

            })
    })

}



chrome.contextMenus.onClicked.addListener((target, tab) => {
    if (target.menuItemId == 'ENCHI') {
        chrome.storage.sync.get('isLogin', (data) => {
            isLogin = data.isLogin;
            if (isLogin) {
                SaveEntry(target.selectionText, target.pageUrl)
            } else {
                chrome.tabs.query({ url: baseUrl }, (tabs) => {
                    if (tabs.length > 0) {
                        let tabIds = []
                        tabs.map((item) => {
                            tabIds.push(item.id)
                        })
                        chrome.tabs.remove(tabIds)
                    }
                })
                chrome.tabs.create({ url: baseUrl });
            }
        })
    }

});

chrome.storage.onChanged.addListener(({ checkUser }) => {
    if (typeof checkUser === 'undefined') return
    if (checkUser.newValue) {
    }
})

chrome.cookies.onChanged.addListener(
    (changeInfo) => {
        if (changeInfo.cookie.domain == 'enchi.io') {
        }

    }
)

